import os

from flask import Flask, render_template, jsonify, request
from flask_cors import CORS
import datetime
from cnn import train_and_predict
from models.news import news_all
from models.user import select_user
from models.weather import get_weather, calculate_average_temperature, get_temperature_level
from models.weathertype import get_weather_statistics
from predicte.pre import count_pre

app = Flask(__name__)

CORS(app, resources={r"/*": {"origins": "*"}})



UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'csv'}
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': '未选择文件'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '空文件名'}), 400
    if file and allowed_file(file.filename):
        filename = 'current_data.csv'  # 统一保存文件名
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(filepath)
        return jsonify({'message': '文件上传成功', 'path': filepath}), 200
    return jsonify({'error': '仅支持CSV文件'}), 400

@app.route('/predict')
def predict():
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], 'current_data.csv')

    if not os.path.exists(filepath):
        return jsonify({'error': '请先上传数据文件'}), 400

    # 调用训练预测函数
    result = train_and_predict(filepath)
    # 调用训练预测函数
    # result = train_and_predict("weather.csv")  # 确保CSV路径正确

    # 处理预测结果
    predictions = result['predictions']

    # 准备图表数据

    # 准备图表数据
    dates = [(datetime.date.today() + datetime.timedelta(days=i + 1)).strftime("%Y-%m-%d")
             for i in range(15)]

    # 折线图数据 - 转换 float32 为 float
    chart1_data = {
        'dates': dates,
        'high_temps': [round(float(p['high_temp']), 1) for p in predictions],
        'low_temps': [round(float(p['low_temp']), 1) for p in predictions]
    }

    # 饼图数据
    avg_temps = [(float(p['high_temp']) + float(p['low_temp'])) / 2 for p in predictions]
    total_avg = sum(avg_temps)
    if total_avg == 0:
        chart2_data = [{'name': f'Day {i + 1}', 'value': 0.0} for i in range(15)]
    else:
        chart2_data = [{
            'name': f'Day {i + 1}',
            'value': round((avg_temps[i] / 15) / total_avg * 100, 2)
        } for i in range(15)]

    # 训练曲线数据 - 转换所有数值为 float
    chart3_data = {
        'epochs': list(range(1, len(result['train_loss']) + 1)),
        'train_loss': [float(round(l, 4)) for l in result['train_loss']],
        'test_loss': [float(round(l, 4)) for l in result['test_loss']],
        'train_rmse': [float(round(r, 4)) for r in result['train_rmse']],
        'test_rmse': [float(round(r, 4)) for r in result['test_rmse']]
    }

    # 表格数据 - 转换 float32 为 float
    table_data = [{
        'high': float(p['high_temp']),
        'low': float(p['low_temp']),
        'avg': (float(p['high_temp']) + float(p['low_temp'])) / 2
    } for p in predictions]

    return jsonify({
        'chart1': chart1_data,
        'chart2': chart2_data,
        'chart3': chart3_data,
        'table': table_data
    })
@app.route('/api/weather/<city>', methods=['GET'])
def weather_data(city):
    try:
        weather_list = get_weather(city)
        if not weather_list:
            return jsonify({"error": "无法获取天气数据"}), 500

        # 计算平均气温并获取最高气温和最低气温
        average_weather_data, overall_avg_temperature, highest_temp, lowest_temp = calculate_average_temperature(weather_list)
        level = get_temperature_level(overall_avg_temperature)

        return jsonify({
            "city": city,
            "weather_data": average_weather_data,
            "level": level,
            "average_temperature": overall_avg_temperature,
            "highest_temperature": highest_temp,
            "lowest_temperature": lowest_temp
        })
    except Exception as e:
        # 记录异常信息
        print(f"Error in fetching weather data for city {city}: {str(e)}")
        return jsonify({"error": "Internal server error"}), 500


@app.route('/api/news', methods=['GET'])
def get_news():
    news_data = news_all()
    if news_data is not None:
        return jsonify(news_data)
    else:
        return jsonify({"error": "Failed to retrieve news data"}), 500

@app.route('/weather_stats', methods=['GET'])
def weather_stats_api():
    city = request.args.get('city')
    if not city:
        return jsonify({"error": "请提供城市名称"}), 400
    stats = get_weather_statistics(city)
    if stats is None:
        return jsonify({"error": "获取天气统计信息时出错"}), 500
    return jsonify(stats)


if __name__ == '__main__':
    app.run(debug=True)
